package com.river.springbootdemo.thinkingjava.io;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class GetChannel {
    private static final int BSIZE = 1024;

    public static void main(String[] args) throws IOException {
        //write a file
        FileChannel channel = new FileOutputStream("d://data.txt").getChannel();
        channel.write(ByteBuffer.wrap("Some text".getBytes()));
        channel.close();

        //add to the end of the file
        channel = new RandomAccessFile("d://data.txt","rw").getChannel();
        channel.position(channel.size());
        channel.write(ByteBuffer.wrap("Some more".getBytes()));
        channel.close();

        //read the file
        channel = new FileInputStream("d://data.txt").getChannel();
        ByteBuffer allocate = ByteBuffer.allocate(BSIZE);
        channel.read(allocate);
        allocate.flip();
        while (allocate.hasRemaining()){
            System.out.print((char) allocate.get());
        }
    }
}
